package zhoug.zui.autocomplete;

import android.content.Context;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * 自动补全提示列表数据适配器
 *
 * @Author: zhoug
 * @Date: 2023-11-01
 * @Description:
 */
public abstract class ZUIAutoCompleteAdapter<T> extends BaseAdapter implements Filterable {
    protected List<T> mData;
    protected Filter mFilter;
    protected Context mContext;
    protected boolean multiSelect;
    protected String mInputText;//输入框中显示的文字

    public ZUIAutoCompleteAdapter() {
        mData=new ArrayList<>();
    }

    public ZUIAutoCompleteAdapter(Context context) {
        this.mContext = context;
        mData=new ArrayList<>();
    }



    public List<T> getData() {
        return mData;
    }

    public void setFilter(Filter filter) {
        this.mFilter = filter;
    }

    @Override
    public int getCount() {
        return mData != null ? mData.size() : 0;
    }


    @Override
    public T getItem(int position) {
        if (mData != null && position < mData.size()) {
            return mData.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public Filter getFilter() {
        return mFilter;
    }

    public void notifyDataSetChanged(List<T> newData) {
        if (mData == null) {
            mData = new ArrayList<>();
        } else {
            mData.clear();
        }
        if (newData != null && newData.size() > 0) {
            mData.addAll(newData);
        }
        notifyDataSetChanged();
    }


    public void setInputText(String inputText) {
        if (!Objects.equals(mInputText, inputText)) {
            this.mInputText = inputText;
            notifyDataSetChanged();
        }
    }

    public String getInputText() {
        return mInputText;
    }

    /**
     * 是否选中
     *
     * @param itemData 点击的item选项
     * @return
     */
    public boolean isSelected(Object itemData) {
        if (itemData != null) {
            String itemName = convertResultToString(itemData);
            if (itemName != null && mInputText != null) {
                return mInputText.contains(itemName);
            }
        }
        return false;
    }

    public String convertResultToString(Object itemData) {
        if (mFilter != null) {
            CharSequence charSequence = mFilter.convertResultToString(itemData);
            return charSequence != null ? charSequence.toString() : null;
        }
        return null;
    }


    public boolean isMultiSelect() {
        return multiSelect;
    }

    public void setMultiSelect(boolean multiSelect) {
        this.multiSelect = multiSelect;
    }
}
